package com.gskj.eduservice.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gskj.eduservice.entity.*;
import com.gskj.eduservice.entity.frontVO.CourseFrontVO;
import com.gskj.eduservice.entity.frontVO.CourseWebVO;
import com.gskj.eduservice.entity.vo.CoursePublishVO;
import com.gskj.eduservice.entity.vo.CourseQueryVO;
import com.gskj.eduservice.entity.vo.CourseVO;
import com.gskj.eduservice.mapper.EduCourseMapper;
import com.gskj.eduservice.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gskj.servicebase.exceptionhandler.GuLiException;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 课程 服务实现类
 * </p>
 *
 * @author testjava
 * @since 2020-05-16
 */
@Service
public class EduCourseServiceImpl extends ServiceImpl<EduCourseMapper, EduCourse> implements IEduCourseService {

    @Autowired
    private IEduCourseDescriptionService iEduCourseDescriptionService;

    @Autowired
    private IEduTeacherService iEduTeacherService;

    @Autowired
    private IEduChapterService iEduChapterService;

    @Autowired
    private IEduVideoService iEduVideoService;

    // 添加课程的相关信息
    @Override
    public String saveCourseInfo(CourseVO courseVO) {

        // 1.添加课程信息
        EduCourse eduCourse = new EduCourse();

        BeanUtils.copyProperties(courseVO, eduCourse);

        int insert = baseMapper.insert(eduCourse);

        if (insert <= 0) {
            // 添加失败
            throw new GuLiException(20001, "添加课程信息失败");
        }

        // 获取添加课程后的id
        String id = eduCourse.getId();

        // 2.添加课程描述简介信息
        EduCourseDescription t = new EduCourseDescription();
        // 赋值
        t.setDescription(courseVO.getDescription());

        // 手动赋值给 课程简介。 使其与课程建立 一对一的关联关系
        t.setId(id);

        boolean save = iEduCourseDescriptionService.save(t);

        if (!save) {
            throw new GuLiException(20001, "添加课程简介失败");
        }
        return id;
    }

    @Override
    public CourseVO getCourseById(String courseId) {
        // 1. 查询课程表
        EduCourse eduCourse = baseMapper.selectById(courseId);
        // 2.查询课程描述表
        EduCourseDescription description = iEduCourseDescriptionService.getById(courseId);

        // 拼接到 CourseVO
        CourseVO courseVO = new CourseVO();

        BeanUtils.copyProperties(eduCourse, courseVO);
        courseVO.setDescription(description.getDescription());
        return courseVO;
    }

    @Override
    public void updateCourseInfo(CourseVO courseVO) {
        // 修改 课程
        EduCourseDescription eduCourseDescription = new EduCourseDescription();
        // 修改 课程描述
        EduCourse eduCourse = new EduCourse();

        // 将视图对象属性 封装到 课程、课程描述
        BeanUtils.copyProperties(courseVO, eduCourse);

        eduCourseDescription.setId(courseVO.getId());
        eduCourseDescription.setDescription(courseVO.getDescription());
        try {
            // 修改 课程
            int i = baseMapper.updateById(eduCourse);
            if (i <= 0) {
                throw new GuLiException(20001, "修改课程基本信息失败！");
            }
            // 修改 课程描述
            boolean b = iEduCourseDescriptionService.updateById(eduCourseDescription);
            if (!b) {
                throw new GuLiException(20001, "修改课程描述信息失败！");
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new GuLiException(20001, "修改课程基本信息失败！");
        }
    }

    @Override
    public CoursePublishVO getCoursePublishInfoByid(String courseId) {
        CoursePublishVO coursePublishInfo = baseMapper.getCoursePublishInfo(courseId);

        return coursePublishInfo;
    }

    @Override
    public void removeCourseById(String courseId) {

        // 查询要删除的 课程
        EduCourse remEduCourse = baseMapper.selectById(courseId);

        // 课程id
        String remCourseId = remEduCourse.getId();

        // 讲师id
        String remTeacherId = remEduCourse.getTeacherId();

        try {
            // 1.  根据 讲师id 删除讲师，删除课程不能将讲师也删除！
//            iEduTeacherService.removeById(remTeacherId);

            // 2. 根据课程id 删除描述
            iEduCourseDescriptionService.removeById(remCourseId);

            // 3. 根据课程id 删除小结以及小结的视频信息
            iEduVideoService.deleteVideoByCourseId(remCourseId);

            // 4. 根据课程id 删除章节
            QueryWrapper<EduChapter> chapterQueryWrapper = new QueryWrapper<>();
            chapterQueryWrapper.eq("course_id", remCourseId);
            iEduChapterService.remove(chapterQueryWrapper);

            // 5.根据课程id 删除课程
            int i = baseMapper.deleteById(remCourseId);

            if (i == 0) {
                throw new GuLiException(20001, "删除课程信息失败！");
            }

        } catch (Exception e) {
            e.printStackTrace();
            throw new GuLiException(20001, "删除课程相关信息失败！");
        }
    }

    @Override
    public Map<String, Object> queryCoursePage(CourseQueryVO queryVO, Integer page, Integer size) {

        // 创建page对象
        Page<EduCourse> eduCoursePage = new Page<>(page, size);

        // 创建查询条件
        QueryWrapper<EduCourse> wrapper = new QueryWrapper<>();
        // 构建查询条件
        String name = queryVO.getName();
        String status = queryVO.getStatus();

        // 非空判断
        if (!StringUtils.isEmpty(name)) {
            wrapper.like("title", name);
        }
        if (!StringUtils.isEmpty(status)) {
            wrapper.eq("status", status);
        }
        // 根据创建时间 排序
        wrapper.orderByDesc("gmt_create");

        // 查询 分页
        baseMapper.selectPage(eduCoursePage, wrapper);


        // 集合
        List<EduCourse> records = eduCoursePage.getRecords();
        // 总记录数
        long total = eduCoursePage.getTotal();

        Map<String, Object> map = new HashMap<>();
        map.put("total", total);
        map.put("row", records);

        return map;
    }

    @Override
    public Map<String, Object> getFrontCourseListCondition(Page<EduCourse> eduCoursePage, CourseFrontVO courseFrontVO) {

        // 拼接分页条件
        QueryWrapper<EduCourse> wrapper = new QueryWrapper<>();

        // 条件非空判断
        String subjectParentId = courseFrontVO.getSubjectParentId();// 一级分类
        String subjectId = courseFrontVO.getSubjectId(); // 二级分类
        String priceSort = courseFrontVO.getPriceSort();// 根据价格排序
        String gmtCreateSort = courseFrontVO.getGmtCreateSort();// 最新时间排序
        String buyCountSort = courseFrontVO.getBuyCountSort(); //关注度排序

        // 查询条件
        if (!StringUtils.isEmpty(subjectParentId)) {
            wrapper.eq("subject_parent_id", subjectParentId);
        }
        if (!StringUtils.isEmpty(subjectId)) {
            wrapper.eq("subject_id", subjectId);
        }

        // 排序条件
        if (!StringUtils.isEmpty(priceSort)) {
            wrapper.orderByDesc("price"); // 价格
        }
        if (!StringUtils.isEmpty(gmtCreateSort)) {
            wrapper.orderByDesc("gmt_create"); // 创建时间
        }
        if (!StringUtils.isEmpty(buyCountSort)) {
            wrapper.orderByDesc("buy_count"); // 销售量
        }

        baseMapper.selectPage(eduCoursePage, wrapper);

        // 将查询的分页数据封装到 map
        Map<String, Object> map = new HashMap<>();

        long current = eduCoursePage.getCurrent();
        long total = eduCoursePage.getTotal();
        List<EduCourse> records = eduCoursePage.getRecords();
        long pages = eduCoursePage.getPages();
        long size = eduCoursePage.getSize();// 每页显示条数

        boolean hasNext = eduCoursePage.hasNext(); // 下一页
        boolean hasPrevious = eduCoursePage.hasPrevious(); // 上一页

        // 封装到 map并返回
        map.put("current", current);
        map.put("pages", pages);
        map.put("items", records);
        map.put("total", total);
        map.put("size", size);
        map.put("hasNext", hasNext);
        map.put("hasPrevious", hasPrevious);

        return map;
    }

    @Override
    public CourseWebVO getBaseCourseInfoById(String courseId) {

        return baseMapper.getBaseCourseInfoById(courseId);
    }
}
